Imports System.Windows.Forms

Public Class frmCalcDO

    Private Sub frmCalcDO_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        SaveControlValues(REGAPP, Me)
    End Sub

    Private Sub frmCalcDO_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Project.DB.FillPickList(cboCCode, "", "CCodes", "CCode", "CCode_Name", "(Create New)")
        frmCalc.RefreshTableList(cboTableName)
        GetControlValues(REGAPP, Me)
    End Sub

    Private Sub cboTableName_SelectionChangeCommitted(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboTableName.SelectionChangeCommitted
        frmCalc.TableSelectionCommitted(cboTableName)
    End Sub

    Private Sub btnNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNext.Click
        Try
            Dim CCode As String = Project.DB.GetPickList(cboCCode)
            If CCode.StartsWith("(Create") Then
                WarningMsg("You must select a valid CCode before continuing.")
                Exit Sub
            End If

            With TabControl1
                If .SelectedIndex = 1 Then
                    Dim TableName As String = cboTableName.Text
                    If cboTableName.SelectedIndex = 0 Then TableName = ActiveBrowser.FullTableName
                    Dim DataTable As New clsDataTable(Project, TableName)
                    DataTable.BeginTransaction()

                    Try
                        'save computed values to table
                        With Project.DataSet.Tables("CrossTab")
                            Dim NumCols As Integer = 0
                            If cboDoSat.SelectedIndex <> 0 Then NumCols += 1
                            If cboPctSat.SelectedIndex <> 0 Then NumCols += 1
                            If cboDoDef.SelectedIndex <> 0 Then NumCols += 1
                            Dim NumComputed As Integer = NumCols * .Rows.Count
                            If MessageBox.Show(StringFormat("You are about to append {0} computed values to the selected Working table ({1}). These were calculated based upon the input PCodes you selected for DO ({2}) and water temperature ({3}). The calculated values will use one or more of the following PCodes:\n\nDO Saturation:\t{4}\nPercent Saturation:\t{5}\nDO Deficit:\t{6}\n\nNote that all existing records having these PCodes will be DELETED before the newly calculated ones are added.\n\nAll new values will use the CCode that you specified ({7}).\n\nBecause the table will be permanently modified, it may be difficult to undo this operation. Are you sure you want to continue?", NumComputed, TableName, cboDO.Text, cboTemp.Text, cboDoSat.Text, cboPctSat.Text, cboDoDef.Text, cboCCode.Text), "Calculate DO Saturation", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = Windows.Forms.DialogResult.OK Then
                                Dim PCode() As String = {Project.DB.GetPickList(cboDoSat), Project.DB.GetPickList(cboPctSat), Project.DB.GetPickList(cboDoDef)}
                                MainForm.WriteProgress("Deleting old records...")
                                For c As Integer = 0 To 2
                                    If Not PCode(c).StartsWith("(") Then
                                        DataTable.DeleteRecords("PCode='{0}'", PCode(c))
                                    End If
                                Next c
                                Try
                                    For i As Integer = 0 To .Rows.Count - 1
                                        Dim r As DataRow = .Rows(i)
                                        For c As Integer = 0 To 2
                                            If Not PCode(c).StartsWith("(") Then
                                                Dim dataRecord As New clsDataRecord(r.Item(0), r.Item(1), PCode(c), r.Item(c + 4), CCode)
                                                If Not DataTable.InsertRecord(dataRecord) Then WarningMsg("Unable to update table.") : Exit Sub
                                            End If
                                        Next c
                                        MainForm.WriteProgress(i, .Rows.Count - 1, "Saving computed values...", ProgressBarStyle.Continuous)
                                    Next
                                    DataTable.Close(clsDataTable.enumEndTransaction.Commit)
                                    IniFile.SetKey(clsWRDBIniFile.enumSection.Application, clsWRDBIniFile.enumKey.AppLastEditTime, Now.ToString(System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat))
                                Catch ex As Exception
                                    DataTable.Close(clsDataTable.enumEndTransaction.Rollback)
                                Finally
                                    DataTable.Close()
                                End Try
                                Project.UpdateTrackingRecord(TableName, , True)
                                MainForm.OpenDataTable(TableName)
                                Project.DataSet.Tables.Remove("CrossTab")
                                Close()
                            End If
                        End With
                    Catch ex As Exception
                        Throw
                    Finally
                        DataTable.Close()
                    End Try
                Else
                    .SelectedIndex += 1
                End If
            End With
        Catch ex As Exception
            ErrorMsg(, ex)
        Finally
            MainForm.ProgressComplete()
            IniFile.Save()
        End Try
    End Sub

    Private Sub TabControl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
        Try
            Select Case TabControl1.SelectedIndex
                Case 1
                    Dim NotSelected As Boolean = False
                    For i As Integer = 1 To 6
                        With CType(Choose(i, cboDO, cboTemp, cboDoSat, cboPctSat, cboDoDef, cboCCode), ComboBox)
                            If .SelectedIndex = -1 Then NotSelected = True : Exit For
                        End With
                    Next
                    If NotSelected Then
                        WarningMsg("You must specify all PCodes and the CCode before you can continue.")
                        TabControl1.SelectedIndex = 0
                        Exit Sub
                    End If
            End Select
            If TabControl1.SelectedIndex = 1 Then
                btnNext.Text = "&Finish"
            Else
                btnNext.Text = "&Next"
            End If
            Select Case TabControl1.SelectedIndex
                Case 1
                    Project.DB.AddTable(Project.DataSet, "CrossTab", String.Format("SELECT D1.Station_ID AS Station_ID,D1.Date_Time AS Date_Time,D1.Result as DO_,D2.Result as TEMP,0.0 as DO_Sat,0.0 as Pct_Sat,0.0 as DO_Def FROM {0} D1, {0} D2 WHERE D1.Station_ID=D2.Station_ID AND D1.Date_Time=D2.Date_Time and D1.PCode='{1}' and D2.PCode='{2}'", clsProject.TempData, Project.DB.GetPickList(cboDO), Project.DB.GetPickList(cboTemp)))
                    For Each r As DataRow In Project.DataSet.Tables("CrossTab").Rows
                        'note: the following equation is from APHA 1985 and relates Temp to DOSat, assuming non-saline water; see clsDataYSI.vb for alternative equation which take into account salinity
                        Dim TK As Double = r.Item(3) + 273.15
                        r.Item(4) = Math.Round(Math.Exp(-139.34411 + 157570.1 / TK - 66423080.0 / TK ^ 2 + 12438000000.0 / TK ^ 3 - 862194900000.0 / TK ^ 4), 2)
                        r.Item(5) = Math.Round(r.Item(2) * 100.0 / r.Item(4), 2)
                        r.Item(6) = Math.Round(r.Item(4) - r.Item(2), 2)
                    Next
                    With dgRecords
                        .DataSource = Project.DataSet.Tables("CrossTab")
                        .ReadOnly = True
                        .RowHeadersVisible = False
                        .AllowUserToAddRows = False
                        .AllowUserToDeleteRows = False
                        .AllowUserToOrderColumns = False
                        .AllowUserToResizeRows = False
                        .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                        For c As Integer = 0 To 6
                            With .Columns(c)
                                .SortMode = DataGridViewColumnSortMode.NotSortable
                                .DefaultCellStyle.Format = Choose(c + 1, "", MyDateTimeFormat, "N2", "N2", "N2", "N2", "N2")
                                .DefaultCellStyle.Alignment = Choose(c + 1, DataGridViewContentAlignment.MiddleLeft, DataGridViewContentAlignment.MiddleCenter, DataGridViewContentAlignment.MiddleRight, DataGridViewContentAlignment.MiddleRight, DataGridViewContentAlignment.MiddleRight, DataGridViewContentAlignment.MiddleRight, DataGridViewContentAlignment.MiddleRight)
                                .AutoSizeMode = Choose(c + 1, DataGridViewAutoSizeColumnMode.AllCells, DataGridViewAutoSizeColumnMode.AllCells, DataGridViewAutoSizeColumnMode.Fill, DataGridViewAutoSizeColumnMode.Fill, DataGridViewAutoSizeColumnMode.Fill, DataGridViewAutoSizeColumnMode.Fill, DataGridViewAutoSizeColumnMode.Fill)
                            End With
                        Next
                    End With
            End Select
        Catch ex As Exception
            ErrorMsg(, ex)
        Finally
            MainForm.ProgressComplete()
        End Try
    End Sub

    Private Sub btnHelp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHelp.Click
        ShowHelp(Me, "6")
    End Sub

    Private Sub cboCCode_SelectionChangeCommitted(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboCCode.SelectionChangeCommitted
        frmCalc.CCodeSelectionCommitted(cboCCode)
    End Sub
End Class
